package com.feiyue.learning.zkclient;

import org.I0Itec.zkclient.IZkDataListener;
import org.I0Itec.zkclient.ZkClient;
import org.I0Itec.zkclient.serialize.SerializableSerializer;
import org.apache.zookeeper.CreateMode;
import org.apache.zookeeper.Watcher;
import org.apache.zookeeper.ZooDefs;
import org.apache.zookeeper.ZooKeeper;

import java.util.concurrent.CountDownLatch;

public class ZkClientDemo {

    private static final String CONNECTION = "127.0.0.1:2181";
    private static final String PATH = "/test";
    private static CountDownLatch countDownLatch = new CountDownLatch(1);

    public static void main(String[] args) throws Exception {

        /* ZooKeeper zk = new ZooKeeper(CONNECTION, 6000, new Watcher() {

            @Override
            public void process(WatchedEvent watchedEvent) {
                // 监听 zookeeper 连接状态的变化
                if (watchedEvent.getState() == Event.KeeperState.SyncConnected) {
                    countDownLatch.countDown();
                    System.out.println("zookeeper 连接状态："  + watchedEvent.getState());
                }
            }
        });*/

        /*
         *  1、使用 zk 原生 api 操作 zk
         */
        ZooKeeper zooKeeper = new ZooKeeper(CONNECTION, 60000, event -> {

            // 监听 zookeeper 连接状态的变化
            if (event.getState() == Watcher.Event.KeeperState.SyncConnected) {
                countDownLatch.countDown();
                System.out.println("zookeeper 连接状态："  + event.getState());
            }

            if (event.getType() == Watcher.Event.EventType.NodeDataChanged) {
                System.out.println("节点数据发生变更");
            }
        });

        countDownLatch.await();
        System.out.println("zookeeper 连接状态：" + zooKeeper.getState());

        // 路径, 数据byte数组, 节点权限 OPEN_ACL_UNSAFE 代表 'world'-'anyone', 节点类型
        zooKeeper.create(PATH, "data".getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);

        // 每次修改数据，如果需要监听的话需要在 getData 的使用注册 watcher(方法 watch 参数值为 true)
        zooKeeper.getData(PATH, true, null);
        zooKeeper.setData(PATH, "test".getBytes(), -1);


        /*
         *  2、使用 zkClient 操作 zk
         */
        // ip+端口, 会话超时时长, 连接超时时长, 序列化器
        ZkClient zkClient = new ZkClient(CONNECTION, 10000, 10000, new SerializableSerializer());


        boolean exists = zkClient.exists(PATH);
        if (!exists) {
            zkClient.createPersistent(PATH);
        }

        // 注册 Watcher
        zkClient.subscribeDataChanges(PATH, new IZkDataListener() {
            @Override
            public void handleDataChange(String s, Object o) throws Exception {

            }

            @Override
            public void handleDataDeleted(String s) throws Exception {

            }
        });

    }
}
